package com.ciwong.epaper.modules.reciteWords.ui;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ciwong.ciwongwrite.widget.CWToast;
import com.ciwong.epaper.R;
import com.ciwong.epaper.common.db.DBCallBack;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.modules.evaluate.bean.WordDetail;
import com.ciwong.epaper.modules.reciteWords.dbreciteword.DBManagerAsyn;
import com.ciwong.epaper.modules.reciteWords.util.WordJumpManager;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.libs.audio.play.AudioPlayer;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.ui.BaseActivity;

import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;

import static com.ciwong.epaper.modules.reciteWords.ui.ReciteWordDetailActivity.INTENT_FROM_WORD_STUDY_ACTIVITY;

public class WordStudyActivity extends BaseActivity implements View.OnClickListener,NextStepLinstener
{

    private ViewGroup container;

    private CopyOnWriteArrayList<WordDetail> todayWords=new CopyOnWriteArrayList<WordDetail>();

    private CopyOnWriteArrayList<WordDetail> reviewWords=new CopyOnWriteArrayList<WordDetail>();

    private CopyOnWriteArrayList<WordDetail> reviewWordsRecord;

    private ArrayList<WordDetail> options=new ArrayList<WordDetail>();

    private WordDetail currentWordDetail;
    private WordDetail lastWordDetail;

    private StudyWordMoudleView studyWordMoudleView;

    private int CURRENR_NEW_INDEX=0;//学习单词当前索引值



    private int REVIEW_WORDS_TO_REVIEW=0;//需复习单词个数

    private  int study_type=0;


    public static  int  REVIEW_YESTERDAY_WORD=1;//复习昨日单词

    public static  int  STUDY_TODAY_WORD=2;//学习今日单词

    public static  int  REVIEW_TODAY_WORD=3;//复习今日单词第一遍

    public static  int REVIEW_TODAY_WORD_SECOND=4;//复习今日单词第二遍

    public static  int REVIEW_TODAY_WORD_THIRD=5;//复习今日单词第3遍

    private ImageView word_study_home;

    private TextView word_study_new_num_tv,word_study_old_num,word_study_name_tv;

    public static final int SOUND_ERROR = R.raw.error;
    public static final int SOUND_RIGHT = R.raw.right;

    LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

    @Override
    public void nextStep(String moudle) {
        try{
            lastWordDetail=currentWordDetail;
            if(study_type==0||study_type==REVIEW_YESTERDAY_WORD){
                CURRENR_NEW_INDEX++;
                saveRecord();
                if(CURRENR_NEW_INDEX<reviewWords.size()){
                    reViewWord(false);
                }else {//昨日单词已经复习完成
                    study_type=STUDY_TODAY_WORD;//开始学习今日单词
                    CURRENR_NEW_INDEX=0;
                    studyTodayNewWords();
                }
            }else if(study_type==STUDY_TODAY_WORD)
            {//学习今日单词

                CURRENR_NEW_INDEX++;
                saveRecord();
                if(CURRENR_NEW_INDEX<todayWords.size()){
                    studyTodayNewWords();
                }else {//今日单词已经学完  开始复习今日单词
                    study_type=REVIEW_TODAY_WORD;//开始学习今日单词
                    CURRENR_NEW_INDEX=0;
                    reViewWord(true);
                }


            }else if(study_type==REVIEW_TODAY_WORD)
            {//学习今日单词

                CURRENR_NEW_INDEX++;
                if(moudle.equals("VOICE_TO_CHINESE")){
                    todayWords.get(CURRENR_NEW_INDEX-1).getMoudleReview().remove("VOICE_TO_CHINESE");
                }else if(moudle.equals("CHINESE_TO_ENGLISH")){
                    todayWords.get(CURRENR_NEW_INDEX-1).getMoudleReview().remove("CHINESE_TO_ENGLISH");
                }else if(moudle.equals("ENGLISH_TO_CHINESE")){
                    todayWords.get(CURRENR_NEW_INDEX-1).getMoudleReview().remove("ENGLISH_TO_CHINESE");
                }else {
                    //当发生错误跳过时 移除第一个
                    if(todayWords.get(CURRENR_NEW_INDEX-1).getMoudleReview().size()>0){
                        todayWords.get(CURRENR_NEW_INDEX-1).getMoudleReview().remove(0);
                    }
                }
                saveRecord();
                if(CURRENR_NEW_INDEX<todayWords.size()){
                    reViewWord(true);
                }else {//今日单词已经学完  开始复习今日单词
                    study_type=REVIEW_TODAY_WORD_SECOND;//开始学习今日单词
                    CURRENR_NEW_INDEX=0;
                    reViewWord(true);
                }


            }else if(study_type==REVIEW_TODAY_WORD_SECOND)
            {//学习今日单词

                CURRENR_NEW_INDEX++;
                if(moudle.equals("VOICE_TO_CHINESE")){
                    todayWords.get(CURRENR_NEW_INDEX-1).getMoudleReview().remove("VOICE_TO_CHINESE");
                }else if(moudle.equals("CHINESE_TO_ENGLISH")){
                    todayWords.get(CURRENR_NEW_INDEX-1).getMoudleReview().remove("CHINESE_TO_ENGLISH");
                }else if(moudle.equals("ENGLISH_TO_CHINESE")){
                    todayWords.get(CURRENR_NEW_INDEX-1).getMoudleReview().remove("ENGLISH_TO_CHINESE");
                }else {
                    //当发生错误跳过时 移除第一个
                    if(todayWords.get(CURRENR_NEW_INDEX-1).getMoudleReview().size()>0){
                        todayWords.get(CURRENR_NEW_INDEX-1).getMoudleReview().remove(0);
                    }
                }
                saveRecord();
                if(CURRENR_NEW_INDEX<todayWords.size()){
                    reViewWord(true);
                }else {//今日单词已经学完  开始复习今日单词
                    study_type=REVIEW_TODAY_WORD_THIRD;//开始学习今日单词
                    CURRENR_NEW_INDEX=0;
                    reViewWord(true);
                }


            }else if(study_type==REVIEW_TODAY_WORD_THIRD)
            {//学习今日单词

                CURRENR_NEW_INDEX++;
                if(moudle.equals("VOICE_TO_CHINESE")){
                    todayWords.get(CURRENR_NEW_INDEX-1).getMoudleReview().remove("VOICE_TO_CHINESE");
                }else if(moudle.equals("CHINESE_TO_ENGLISH")){
                    todayWords.get(CURRENR_NEW_INDEX-1).getMoudleReview().remove("CHINESE_TO_ENGLISH");
                }else if(moudle.equals("ENGLISH_TO_CHINESE")){
                    todayWords.get(CURRENR_NEW_INDEX-1).getMoudleReview().remove("ENGLISH_TO_CHINESE");
                }else {
                    //当发生错误跳过时 移除第一个
                    if(todayWords.get(CURRENR_NEW_INDEX-1).getMoudleReview().size()>0){
                        todayWords.get(CURRENR_NEW_INDEX-1).getMoudleReview().remove(0);
                    }
                }
                saveRecord();
                if(CURRENR_NEW_INDEX<todayWords.size()){
                    reViewWord(true);
                }else {//今日单词已经学完  开始复习今日单词
                    //学习结束
                    //
                    CWSys.setSharedLong(ListenSpeakUtil.getCompleteTimeKey(),System.currentTimeMillis());
                    ArrayList<Integer> wordIndexArray = new ArrayList<>();
                    for (WordDetail todayWord : todayWords) {
                        wordIndexArray.add(Integer.parseInt(todayWord.getdId()));
                    }
                    WordJumpManager.jumpToDaKaActivity(R.string.go_back, WordStudyActivity.this,wordIndexArray);
                    finish();
                }

            }

        }catch (Exception e){
            e.getStackTrace();
            com.ciwong.epaper.modules.reciteWords.util.WordUtil.clearStudyRecord();
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //继续学习
        studyWordMoudleView.updataui();

    }

    @Override
    protected void preCreate() {
        super.preCreate();
        try{
            //去除title
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            //去掉Activity上面的状态栏
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }catch (Exception e){
            e.getStackTrace();
        }

    }

    @Override
    protected int setView()
    {
        return R.layout.word_study;
    }

    @Override
    protected void findViews() {
        container=findViewById(R.id.container);

    }

    @Override
    protected void initEvent() {
        word_study_home=findViewById(R.id.word_study_home);
        word_study_new_num_tv=findViewById(R.id.word_study_new_num_tv);
        word_study_old_num=findViewById(R.id.word_study_old_num);
        word_study_name_tv=findViewById(R.id.word_study_name_tv);
    }

    @Override
    protected void onPause() {
        super.onPause();
        saveRecord();
        AudioPlayer.getInstance().stop();
    }



    @Override
    protected void init() {
        hideTitleBar();
        word_study_home.setOnClickListener(this);
        word_study_name_tv.setOnClickListener(this);

    }

    @Override
    protected void loadData() {
        try{
            ArrayList<WordDetail> wordDetails=( ArrayList<WordDetail>)getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_NEW_WORD);
            todayWords.addAll(wordDetails);
            ArrayList<WordDetail> wordDetails1=( ArrayList<WordDetail>)getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_REVIEW_WORD);
            reviewWords.addAll(wordDetails1);
            study_type=CWSys.getSharedInt(ListenSpeakUtil.getStudyTypeKey(),0);
            CURRENR_NEW_INDEX= CWSys.getSharedInt(ListenSpeakUtil.getCurrentNewWordKey(),0);



            REVIEW_WORDS_TO_REVIEW= CWSys.getSharedInt(ListenSpeakUtil.getReviewWordToReviewKey(),0);

            if(study_type==0)
            {//还没学习记录
                CURRENR_NEW_INDEX=0;
                if(reviewWords.size()>0){
                    reViewWord(false);
                }else {
                    if(todayWords.size()>0){
                        studyTodayNewWords();
                    }else {
                        CWToast.error(WordStudyActivity.this,"没有要学的单词").show();
                    }
                }

            }else if(study_type==REVIEW_YESTERDAY_WORD)//复习昨日单词
            {
                reViewWord(false);
            }else if(study_type==STUDY_TODAY_WORD)//学习今日单词
            {
                studyTodayNewWords();

            }else if(study_type==REVIEW_TODAY_WORD||
                    study_type==REVIEW_TODAY_WORD_SECOND||study_type==REVIEW_TODAY_WORD_THIRD)//复习单词今日第一遍 复习单词今日第2遍 复习单词今日第3遍
            {
                SerializableManager.getInstance().deSerialize(
                        ListenSpeakUtil.getReviewNewWordKey(),
                        new BaseCallBack() {
                            @Override
                            public void success(Object data) {
                                try {
                                    if (data != null) {
                                        reviewWordsRecord = (CopyOnWriteArrayList<WordDetail>) data;
                                        if(reviewWordsRecord!=null&&todayWords!=null){
                                            for (WordDetail w:todayWords
                                                    ) {
                                                for (WordDetail r:reviewWordsRecord
                                                        ) {
                                                    if(r.getdId().equals(w.getdId())){
                                                        w.setMoudleReview(r.getMoudleReview());
                                                    }
                                                }
                                            }
                                        }


                                        saveRecord();
                                        reViewWord(true);


                                    }else {
                                        reViewWord(true);

                                    }

                                }catch (Exception e){
                                    e.getStackTrace();
                                }


                            }

                            @Override
                            public void failed(int errorCode, Object data) {
                                reViewWord(true);
                            }

                            @Override
                            public void failed(Object data) {
                                reViewWord(true);
                            }
                        });
            }

        }catch (Exception e){
            e.getStackTrace();
            com.ciwong.epaper.modules.reciteWords.util.WordUtil.clearStudyRecord();

        }


    }





    @Override
    public void onClick(View view) {
        try{
            if(view.getId()==R.id.word_study_home){
                //回首页
                finish();
            }else if(view.getId()==R.id.word_study_name_tv){
                //挑详情
                if(lastWordDetail!=null){
                    WordJumpManager.jumpToReciteWordDetailActivity(R.string.go_back,WordStudyActivity.this,INTENT_FROM_WORD_STUDY_ACTIVITY,null,lastWordDetail.getdId());
                }
            }
        }catch (Exception e){
            e.getStackTrace();
            com.ciwong.epaper.modules.reciteWords.util.WordUtil.clearStudyRecord();

        }


    }


    /**
     * 新学今天单词
     */

    private void studyTodayNewWords(){
        try {
            DBManagerAsyn.getInstance().executeGetOptionsAsyn("", todayWords.get(CURRENR_NEW_INDEX).getdId(), new DBCallBack() {
                @Override
                public void dbResult(Object data) {
                    options=(ArrayList<WordDetail>) data;
                    Log.e(TAG, "dbResult studyTodayNewWords: "+options.size() );
                    if(options.size()>0){
                        for(WordDetail wordDetail:options){
                            if(wordDetail.getdId().equals(todayWords.get(CURRENR_NEW_INDEX).getdId())){
                                currentWordDetail=wordDetail;
                            }
                        }
                    }

                    if(options.size()==4&&currentWordDetail!=null){
                        study_type=STUDY_TODAY_WORD;//开始学习今日单词

                        REVIEW_WORDS_TO_REVIEW=CURRENR_NEW_INDEX;
                        word_study_new_num_tv.setText("需新学 "+(todayWords.size()-CURRENR_NEW_INDEX));
                        word_study_old_num.setText("需复习 "+(CURRENR_NEW_INDEX));
                        if(lastWordDetail!=null){
                            word_study_name_tv.setText(lastWordDetail.getWords()+" "+lastWordDetail.getPretations());
                        }else {
                            word_study_name_tv.setText("");
                        }
                        EnglishToPicView englishToPicView=new EnglishToPicView(WordStudyActivity.this);
                        englishToPicView.setDataAndUpdataUI(currentWordDetail,options,WordStudyActivity.this);
                        englishToPicView.setLayoutParams(params1);
                        studyWordMoudleView=englishToPicView;
                        container.removeAllViews();
                        container.addView(englishToPicView);

                    }else {
                        //出错处理页面
                        nextStep("");
                    }


                }
            });



        }catch (Exception e){
            e.getStackTrace();
            com.ciwong.epaper.modules.reciteWords.util.WordUtil.clearStudyRecord();

        }
    }

    /**
     * 复习单词  复习昨日单词 和复习今日单词
     */

    private void reViewWord(boolean idToday){
        try{
            if(idToday){
                if(todayWords.size()<=0){
                    return;
                }

                int theNumOfmoudle=todayWords.get(CURRENR_NEW_INDEX).getMoudleReview().size();
                String moudleReview;

                if(theNumOfmoudle!=0&&theNumOfmoudle<=1){
                     moudleReview= todayWords.get(CURRENR_NEW_INDEX).getMoudleReview().get(0);
                }else {
                    int moudle=getMoudle(theNumOfmoudle);
                     moudleReview= todayWords.get(CURRENR_NEW_INDEX).getMoudleReview().get(moudle);
                }

                word_study_new_num_tv.setText("需新学 0");
                if(study_type==REVIEW_TODAY_WORD_THIRD){
                    word_study_old_num.setText("需复习 "+(todayWords.size()-CURRENR_NEW_INDEX));
                    REVIEW_WORDS_TO_REVIEW=todayWords.size()-CURRENR_NEW_INDEX;
                }else {
                    REVIEW_WORDS_TO_REVIEW=todayWords.size();
                    word_study_old_num.setText("需复习 "+(todayWords.size()));
                }

                if(lastWordDetail!=null){
                    word_study_name_tv.setText(lastWordDetail.getWords()+" "+lastWordDetail.getPretations());
                }else {
                    word_study_name_tv.setText("");
                }

                loadUI(moudleReview,todayWords.get(CURRENR_NEW_INDEX).getdId());
            }else {
                study_type = REVIEW_YESTERDAY_WORD;
                int moudle=getMoudle(3);
                String moudleReview= reviewWords.get(CURRENR_NEW_INDEX).getMoudleReview().get(moudle);

                REVIEW_WORDS_TO_REVIEW=reviewWords.size()-CURRENR_NEW_INDEX;

                word_study_new_num_tv.setText("需新学 "+todayWords.size());
                word_study_old_num.setText("需复习 "+(reviewWords.size()-CURRENR_NEW_INDEX));
                if(lastWordDetail!=null){
                    word_study_name_tv.setText(lastWordDetail.getWords()+" "+lastWordDetail.getPretations());
                }else {
                    word_study_name_tv.setText("");
                }

                loadUI(moudleReview,reviewWords.get(CURRENR_NEW_INDEX).getdId());
            }
        }catch (Exception e){
            e.getStackTrace();
            com.ciwong.epaper.modules.reciteWords.util.WordUtil.clearStudyRecord();
        }


    }

    private void loadUI(final String moudleReview,final String did){
        try{
            if(moudleReview!=null) {
                DBManagerAsyn.getInstance().executeGetOptionsAsyn("", did, new DBCallBack() {
                    @Override
                    public void dbResult(Object data) {
                        options=(ArrayList<WordDetail>) data;
                        Log.e(TAG, "dbResult loadUI: "+options.size() );
                        if(options.size()>0){
                            for(WordDetail wordDetail:options){
                                if(wordDetail.getdId().equals(did)){
                                    currentWordDetail=wordDetail;
                                }
                            }
                        }
                        if(options.size()==4&&currentWordDetail!=null){
                            if (moudleReview.equals("VOICE_TO_CHINESE")) {
                                VoiceToEnglishView voiceToEnglishView=new VoiceToEnglishView(WordStudyActivity.this);
                                voiceToEnglishView.SteDataAndUpdataUi(currentWordDetail,options,WordStudyActivity.this);
                                voiceToEnglishView.setLayoutParams(params1);
                                studyWordMoudleView=voiceToEnglishView;
                                container.removeAllViews();
                                container.addView(voiceToEnglishView);
                            } else if (moudleReview.equals("CHINESE_TO_ENGLISH")) {
                                ChineseToEnglish chineseToEnglish=new ChineseToEnglish(WordStudyActivity.this);
                                chineseToEnglish.SteDataAndUpdataUi(currentWordDetail,options,WordStudyActivity.this);
                                chineseToEnglish.setLayoutParams(params1);
                                studyWordMoudleView=chineseToEnglish;
                                container.removeAllViews();
                                container.addView(chineseToEnglish);

                            } else if (moudleReview.equals("ENGLISH_TO_CHINESE")) {
                                EnhlishToChinese enhlishToChinese=new EnhlishToChinese(WordStudyActivity.this);
                                enhlishToChinese.SteDataAndUpdataUi(currentWordDetail,options,WordStudyActivity.this);
                                enhlishToChinese.setLayoutParams(params1);
                                studyWordMoudleView=enhlishToChinese;
                                container.removeAllViews();
                                container.addView(enhlishToChinese);
                            }

                           // lastWordDetail=currentWordDetail;
                        }else {
                            //出错处理 跳过
                            nextStep("");
                        }
                    }
                });



            }
        }catch (Exception e){
            e.getStackTrace();
            com.ciwong.epaper.modules.reciteWords.util.WordUtil.clearStudyRecord();
        }



    }

    private int getMoudle(int num){
    try{
        Random random=new Random();
        int  i=random.nextInt(num);
        return i;
    }catch (Exception e){
        e.getStackTrace();
        com.ciwong.epaper.modules.reciteWords.util.WordUtil.clearStudyRecord();
    }

    return 0;
}

    //保存学习记录
    private void saveRecord(){
        try{
            CWSys.setSharedInt(ListenSpeakUtil.getCurrentNewWordKey(),CURRENR_NEW_INDEX);
            CWSys.setSharedInt(ListenSpeakUtil.getReviewWordToReviewKey(),REVIEW_WORDS_TO_REVIEW);
            CWSys.setSharedInt(ListenSpeakUtil.getStudyTypeKey(),study_type);
            SerializableManager.getInstance().serialize( ListenSpeakUtil.getReviewNewWordKey(),todayWords);
        }catch (Exception e){
            e.getStackTrace();
            com.ciwong.epaper.modules.reciteWords.util.WordUtil.clearStudyRecord();

        }

    }
}
